<!DOCTYPE HTML>
<html>
	<head>
		<meta charset="utf-8" />
		<title>PayPal</title>
		<script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script>
	</head>
	
	<body>
		<div id="console">
			Loading...
		</div>
		<script>
			const query = window.location.href.split('?')[1]
	
			const queryObj = query.split('&').reduce((prev, current) => {
				const [key, value] = current.split('=')
				prev[key] = value
				return prev
			}, {})

			var BASE_URL = decodeURIComponent(queryObj.url)
			
			const serializer = (obj) => {
				return Object.entries(obj).reduce((prev, [key, value]) => {
					prev.push(key + '=' + value)
					return prev
				}, []).join('&')
			}
			
			const handleResponse = (data) => {
				const cl = document.getElementById('console')
				
				const response = JSON.parse(data.data)
				
				const formAttr = [
					['id', 'submit-form'],
					['action', response.apiUrl],
					['method', 'POST'],
					['style', 'display: none'],
					['content-type', 'multipart/form-data']
				]
				const form = document.createElement('form')
			
				formAttr.forEach(([key, value]) => {
					form.setAttribute(key, value)
				})
			
				const createInput = attrs => {
					const input = document.createElement('input')
			
					Object.entries(attrs).forEach(([key, value]) => {
						input.setAttribute(key, value || '')
					})
			
					return input
				}
			
				const fragment = document.createDocumentFragment()
	
				const inputAtt = Object.keys(response).map(val => ({
					key: val,
					val: response[val]
				}))
			
				inputAtt.forEach(current => {
					const input = createInput({
						name: current.key,
						value: current.val
					})
					fragment.appendChild(input)
				})
			
				form.appendChild(fragment)
			
				const button = document.createElement('button')
				button.type = 'submit'
				
				form.appendChild(button)
			
				document.body.appendChild(form)
			
				form.submit()
			}
			
			window.onload = function() {
				const xhr = new XMLHttpRequest()
				
				xhr.open('GET', BASE_URL + '/payPal/getPayInfo?isApp=1&orderId=' + queryObj.order_id + '&url=http://www.wharfon.com&jumpUrl=/jump.html', true)
				xhr.setRequestHeader('Authorization', queryObj.token)
				
				xhr.onreadystatechange = function() {
					if (xhr.readyState === XMLHttpRequest.DONE) {
						const status = xhr.status
						
						if (status === 0 || (status >= 200 && status < 400)) {
							const response = JSON.parse(xhr.response)
							
							if (response.code === 200) {
								handleResponse(response)
							}
							
						}
					}
				}
				
				xhr.send(null)
			}
		</script>
	</body>
	
</html>